const balanceApi = require('../../api/balance.js')

Page({
  data: {
    loading: false,
    balance: '0.00',
    availableBalance: '0.00',
    frozenBalance: '0.00',
    totalRecharge: '0.00',
    totalConsume: '0.00',
    rechargeCount: 0,
    recentRecords: [],
    statisticsData: null
  },

  onLoad() {
    this.loadBalanceData()
  },

  onShow() {
    // 从充值页面返回时刷新数据
    this.loadBalanceData()
  },

  // 加载余额数据
  async loadBalanceData() {
    this.setData({ loading: true })

    try {
      // 并行加载余额信息和充值记录
      const [balanceData, recordsData] = await Promise.all([
        this.getUserBalance(),
        this.getRecentRecords()
      ])

      // 处理余额数据
      if (balanceData) {
        // 计算可用余额
        const balance = balanceData.balance || 0
        const frozenBalance = balanceData.frozenBalance || 0
        const availableBalance = balance - frozenBalance

        this.setData({
          balance: this.formatAmount(balance),
          availableBalance: this.formatAmount(availableBalance),
          frozenBalance: this.formatAmount(frozenBalance),
          totalRecharge: this.formatAmount(balanceData.totalRecharge || 0),
          totalConsume: this.formatAmount(balanceData.totalConsume || 0),
          statisticsData: balanceData
        })
      } else {
        // 设置默认值
        this.setData({
          balance: '0.00',
          availableBalance: '0.00',
          frozenBalance: '0.00',
          totalRecharge: '0.00',
          totalConsume: '0.00',
          statisticsData: null
        })
      }

      // 处理充值记录数据
      if (recordsData && recordsData.records) {
        const records = recordsData.records.slice(0, 3) // 只显示最近3条
        this.setData({
          recentRecords: records.map(record => ({
            ...record,
            createTime: this.formatTime(record.createTime),
            rechargeAmount: this.formatAmount(record.rechargeAmount),
            statusName: this.getStatusName(record.status)
          })),
          rechargeCount: recordsData.total || 0
        })
      } else {
        this.setData({
          recentRecords: [],
          rechargeCount: 0
        })
      }

    } catch (error) {
      console.error('加载余额数据失败:', error)
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 获取用户余额
  async getUserBalance() {
    try {
      const data = await balanceApi.getUserBalance()
      return data
    } catch (error) {
      console.error('获取余额失败:', error)
      throw error
    }
  },

  // 获取最近充值记录
  async getRecentRecords() {
    try {
      const data = await balanceApi.getRechargeRecords({
        page: 1,
        size: 3
      })
      return data
    } catch (error) {
      console.error('获取充值记录失败:', error)
      throw error
    }
  },

  // 刷新余额
  refreshBalance() {
    wx.showToast({
      title: '刷新中...',
      icon: 'loading'
    })
    this.loadBalanceData()
  },

  // 跳转到充值页面
  goToRecharge() {
    wx.navigateTo({
      url: '/pages/recharge/recharge'
    })
  },

  // 查看全部充值记录
  viewAllRecords() {
    wx.navigateTo({
      url: '/pages/recharge-records/recharge-records'
    })
  },

  // 查看充值记录
  viewRechargeRecords() {
    wx.navigateTo({
      url: '/pages/recharge-records/recharge-records'
    })
  },

  // 查看消费记录
  viewConsumeRecords() {
    wx.navigateTo({
      url: '/pages/consumption-records/consumption-records',
      fail: (error) => {
        console.error('跳转到消费记录页面失败:', error)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
  },

  // 联系客服
  contactService() {
    wx.showModal({
      title: '客服咨询',
      content: '如有疑问，请联系客服\n电话：400-123-4567\n微信：service001',
      showCancel: false,
      confirmText: '知道了'
    })
  },

  // 格式化金额
  formatAmount(amount) {
    if (!amount && amount !== 0) return '0.00'
    return parseFloat(amount).toFixed(2)
  },

  // 格式化时间
  formatTime(timeStr) {
    if (!timeStr) return ''
    const date = new Date(timeStr)
    const now = new Date()
    const diff = now - date
    
    // 一分钟内
    if (diff < 60000) {
      return '刚刚'
    }
    // 一小时内
    if (diff < 3600000) {
      return `${Math.floor(diff / 60000)}分钟前`
    }
    // 一天内
    if (diff < 86400000) {
      return `${Math.floor(diff / 3600000)}小时前`
    }
    // 一周内
    if (diff < 604800000) {
      return `${Math.floor(diff / 86400000)}天前`
    }
    
    // 超过一周显示具体日期
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    
    return `${month}-${day} ${hour}:${minute}`
  },

  // 获取状态名称
  getStatusName(status) {
    const statusMap = {
      1: '成功',
      0: '处理中',
      '-1': '失败'
    }
    return statusMap[status] || '未知'
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadBalanceData().finally(() => {
      wx.stopPullDownRefresh()
    })
  }
}) 